package zhongbo.javaweb.instagram.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import zhongbo.javaweb.instagram.dto.NextIdDto;

import javax.annotation.PostConstruct;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 说明：
 *
 * @author zhongboWork
 * @version 1.0
 * @since 2022-01-06 15:41
 */
@Service
@Slf4j
public class UserIdService {

    @Autowired
    private FileService<AtomicInteger> fileService;

    private List<String> userIdList;

    private AtomicInteger index;

    private Class<AtomicInteger> tClass;

    @PostConstruct
    public void init() throws IOException {
        userIdList = new ArrayList<>();
        tClass = AtomicInteger.class;
        index = fileService.readJson(tClass);
        if (index == null) {
            index = new AtomicInteger(0);
        }
        String userDir = System.getProperty("user.dir");
        String userIdFileName = "ins_user_id.txt";
        File userIdFile = new File(userDir + File.separator + userIdFileName);
        InputStreamReader reader;
        if (userIdFile.exists() && userIdFile.isFile() && userIdFile.canRead()) {
            reader = new FileReader(userIdFileName);
        } else {
            InputStream resourceAsStream = UserIdService.class.getResourceAsStream("/" + userIdFileName);
            reader = new InputStreamReader(resourceAsStream);
        }
        BufferedReader bufferedReader = new BufferedReader(reader);
        List<String> collect = bufferedReader.lines().collect(Collectors.toList());
        for (String userIdString : collect) {
            if (!StringUtils.isEmpty(userIdString)) {
                userIdList.add(userIdString);
            }
        }
        int size = userIdList.size();
        if (size == 0) {
            throw new RuntimeException("载入用户userId失败!");
        }
        log.info("load userId {}", size);
    }


    public NextIdDto next() {
        int i = index.getAndIncrement();
        if (i >= userIdList.size() || i < 0) {
            reset();
            return next();
        }
        update();
        String id = userIdList.get(i);
        return new NextIdDto(i, id);
    }

    private void update() {
        try {
            fileService.writeJson(index, tClass);
        } catch (IOException e) {
            log.error("update index failed!", e);
        }
    }

    public int current() {
        return index.get();
    }

    public void reset() {
        index.set(0);
        update();
    }

    public void move(int i) {
        index.set(i);
        update();
    }

    public int total() {
        return userIdList.size();
    }
}
